#pragma once

#include "sys/constants.h"
#include "renderer/api/device.h"

namespace embree
{
  extern Device* gEmbreeDevice;

  ////////////////////////////////////////////////////////////////////////////////
  /// Automatic reference counting for Embree Handles
  ////////////////////////////////////////////////////////////////////////////////

  template<typename Type>
  class Handle 
  {
  public:
    
    __forceinline Handle ( void ) : handle(NULL) {}
    __forceinline Handle (NullTy) : handle(NULL) {}
    __forceinline Handle( Type const input ) : handle(input) {}

    __forceinline Handle( const Handle& input ) : handle(input.handle) { 
      if (handle) gEmbreeDevice->rtIncRef(handle);
    }

    __forceinline ~Handle( void ) {
      if (handle) gEmbreeDevice->rtDecRef(handle);
    }

    __forceinline Handle& operator =( const Handle& input )
    {
      if (input.handle) gEmbreeDevice->rtIncRef(input.handle);
      if (handle) gEmbreeDevice->rtDecRef(handle);
      handle = input.handle;
      return *this;
    }

    __forceinline Handle& operator =( NullTy ) {
      if (handle) gEmbreeDevice->rtDecRef(handle);
      handle = NULL;
      return *this;
    }

    __forceinline operator bool() const { return handle != NULL; }
    __forceinline operator Type() const { return handle; }

  private:
    Type handle;
  };
}
